import React, {PropsWithChildren, useEffect, useState} from 'react'
import {TabPane, Tabs, TabsProps} from "@nutui/nutui-react-taro";
import styles from "./LazyTabs.module.sass"

export interface LazyTabsProps extends PropsWithChildren {
    lazyItems: LazyItem[]
    tabStyle?: TabsProps["tabStyle"]
    value?: TabsProps["value"]
    onChange?: (v: string | number) => void
}

export interface LazyItem {
    key: string | number
    label: string
    render: () => React.ReactNode
}

const LazyTabs: React.FC<LazyTabsProps> = (props) => {
    return <>
        <Tabs direction={"horizontal"} {...props} value={props.value} onChange={v => {
            if (props.onChange) {
                props.onChange(v);
            }
        }}>
            {props.lazyItems.map(item => {
                return <TabPane value={item.key} title={item.label} className={styles.panel}>
                    <LazyTabItemComponent activatedKey={props.value} myKey={item.key} render={item.render}/>
                </TabPane>
            })}
        </Tabs>
    </>
}

const LazyTabItemComponent: React.FC<{
    activatedKey?: string | number,
    myKey: string | number,
    render: () => React.ReactNode
}> = (props) => {
    const [loaded, setLoaded] = useState(false)
    useEffect(() => {
        if (!loaded) {
            setLoaded(props.activatedKey === props.myKey)
        }
    }, [props.activatedKey, props.myKey]);
    return (
        <>
            {loaded && props.render()}
        </>
    )
}

export default LazyTabs


